package com.ratingbay.console.restful.view;

import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.JstlView;

import com.ratingbay.console.restful.builder.IRestfulViewContentBuilder;


public class RestfulView extends JstlView {
    @Override
    public void render(Map<String, ?> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        RestfulResponseWrapper restfulResponseWrapper = new RestfulResponseWrapper(response);
        super.render(model, request, restfulResponseWrapper);

        String restfulViewContent = restfulResponseWrapper.getContent();
        String finalViewContent = null;
        String contentType = null;

        IRestfulViewContentBuilder restfulViewContentBuilder = 
            this.getRestfulViewContentBuilder(model);

        if(null == restfulViewContentBuilder){
            finalViewContent = this.getFinalViewContent(restfulViewContent);
            contentType = this.getContentType();
        }else{
            restfulViewContentBuilder.setModel(model);
            finalViewContent = restfulViewContentBuilder.getFinalViewContent(restfulViewContent);
            contentType = restfulViewContentBuilder.getContentType();
        }

        response.setContentType(contentType);
        PrintWriter printWriter = response.getWriter();
        printWriter.write(finalViewContent);
        printWriter.flush();
    }


    protected String getFinalViewContent(String restfulViewContent){
        return restfulViewContent;
    }

    protected IRestfulViewContentBuilder getRestfulViewContentBuilder(Map<String, ?> model){
        return (IRestfulViewContentBuilder) model.get("IRestfulViewContentBuilder");
    }

    public String getContentType(){
        return "text/html;charset=UTF-8";
    }
}
